package com.ccp.dev.workflow.service.jms;

import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.model.MessageModel;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.model.MessageSend;
import com.ccp.dev.system.service.MessageEngine;
import com.ccp.dev.workflow.bpmutil.ServiceUtil;
import com.ccp.dev.workflow.model.SysTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * ClassDescribe:
 * 重写之前的JMS消息处理，直接保存到数据库
 * @author :wangcheng
 * Date: 2019-08-07
 */
@Component
public class MessageProducer {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageProducer.class);
    @Resource
    private MessageEngine messageEngine;

    public void send(Object object) {
        if (object instanceof MessageModel) {
            this.sendInnerMessage((MessageModel)object);
        }
    }

    /**
     * 将消息直接保存到数据库
     * @param model 消息数据对象
     */
    private void sendInnerMessage(MessageModel model) {
        MessageSend messageSend = new MessageSend();
        if (model.getReceiveUser() == null || model.getSendUser() == null) {
            return;
        }

        messageSend.setId(UUIDUtils.getUUIDFor32());
        // 发送人姓名
        messageSend.setUserName(this.getSendUserName(model));
        // 发送人ID
        messageSend.setUserId(model.getSendUser().getUserId());
        messageSend.setSendTime(model.getSendDate());
        messageSend.setMessageType(this.getMessageType(model));
        messageSend.setContent(this.getContent(model));
        messageSend.setSubject(this.getSubject(model));
        messageSend.setCreateBy(model.getSendUser().getUserId());
        // 接收人id
        messageSend.setRid(model.getReceiveUser().getUserId());
        messageSend.setReceiverName(model.getReceiveUser().getFullName());
        messageSend.setCreateTime(model.getSendDate() == null ? new Date() : model.getSendDate());
        messageSend.setTenantId(model.getReceiveUser().getTenantId());
        messageEngine.sendInnerMessage(messageSend);
    }

    /**
     * 获取标题
     * @param model 消息对象
     * @return
     */
    private String getSubject(MessageModel model) {
        if (model.getTemplateMap() == null){
            return model.getSubject();
        }
        // 发送标题
        String title = ServiceUtil.replaceTitleTag(model.getTemplateMap().get(SysTemplate.TEMPLATE_TITLE), model.getReceiveUser().getFullName(), this.getSendUserName(model), model.getSubject(), model.getOpinion());

        return title;
    }

    /**
     * 获取消息内容，内容如果有模板，需要用模板替换
     * @param model 消息对象
     * @return
     */
    private String getContent(MessageModel model) {
        String content = "";
        if (model.getTemplateMap() == null) {
            return model.getContent();
        }

        // 流程运行id或者任务id，由isTask决定
        String id = model.getExtId();
        // 是否是任务（true : 是，false: 不是）
        boolean isTask = model.getIsTask();

        // 链接地址
        String url = "";
        if (StringUtil.isNotEmpty(id)) {
            url = ServiceUtil.getUrl(id, isTask);
        }
        Map vars = model.getVars();
        if (BeanUtils.isNotEmpty(vars)) {
            if (BeanUtils.isNotEmpty(vars.get("copyId"))) {
                String copyId = (String) vars.get("copyId");
                url = url + "&copyId=" + copyId;
            }
        }
        if (StringUtil.isNotEmpty(url)) {
            url = url.replace("http://", "");
            url = url.substring(url.indexOf("/"), url.length());
        }

        // 发送内容
        content = ServiceUtil.replaceTemplateTag(this.getTemplate(model), model.getReceiveUser().getFullName(),
                //流程标题对应的超链接路径       this.getSendUserName(model), model.getSubject(), "${ctx}" + url,
                this.getSendUserName(model), model.getSubject(), url, model.getOpinion(), false);

        try{
            // 处理nodeMsgTemplate
            String htmlDefForm = model.getTemplateMap().get("htmlDefForm");
            String textDefForm = model.getTemplateMap().get("textDefForm");
            if (!StringUtil.isEmpty(htmlDefForm)) {
                content = content.replace("${html表单}", htmlDefForm);
            }
            if(!StringUtil.isEmpty(textDefForm)){
                content = content.replace("${text表单}", textDefForm);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return content;
    }

    /**
     * 获取短信的模板内容
     * @param model 消息对象
     * @return
     */
    private String getTemplate(MessageModel model) {
        String smsTemplate = "";
        try {
            smsTemplate = model.getTemplateMap().get(SysTemplate.TEMPLATE_TYPE_PLAIN);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return smsTemplate;

    }

    /**
     * 获取消息类型
     * @param model 消息对象
     * @return 消息类型
     */
    private String getMessageType(MessageModel model) {
        String msgType = null;
        Map messageType = model.getVars();
        if (null != messageType && !messageType.isEmpty()) {
            Set<String> keySet = messageType.keySet();
            for (String key : keySet) {
                msgType = String.valueOf(messageType.get(key));
            }
        } else {
            msgType = MessageSend.MESSAGETYPE_SYSTEM;
        }

        return msgType;
    }

    /**
     * 获取发信人名称
     * @param model 消息对象
     * @return 发信人名称
     */
    private String getSendUserName(MessageModel model) {
        String sendUserName = "";
        if (model.getSendUser() == null) {
            sendUserName = "系统消息";
        } else {
            sendUserName = model.getSendUser().getFullName();
        }
        return sendUserName;
    }
}
